package xdTool

import groovy.sql.Sql
import model.XdCell
import sysUtil.BeetlUtil
import sysUtil.SysCommUtil

import java.sql.Clob

class XdTableCfg {

    Long widgetPanelId ;
    String elem;//模型名称
    String url ;
    Clob toolbar = SysCommUtil.String2Clob("false")
    List defaultToolbar = ['filter','print']
    String width;
    String height = "full-100";
    String cellMinWidth = "60";//列宽自动分配
    String totalRow = "true";//是否开启合计
    String page = "false";//是否分页
    String title ;
    String domId ;
    String skin ;//皮肤
    String size_ ; //表格尺寸、lg、sm
    String even  ; //隔行背景
    String queryFlag = "true" //进入页面查询
    String autoFlag = "false" //自动刷新
    String autoInterval
    String creator ;//操作人
    String updater;//最近一次更新人
    Date dateCreated;
    Date lastUpdated;
    static constraints = {
        elem(nullable: false,blank: false )
        widgetPanelId(nullable: false)
        toolbar(nullable: true)
        width(nullable: true)
        url(nullable: true)
        height(nullable: true)
        cellMinWidth(nullable: true)
        totalRow(nullable: true)
        page(nullable: true)
        title(nullable: true)
        domId(nullable: true)
        skin(nullable: true)
        size_(nullable: true)
        even(nullable: true)
        queryFlag(nullable: true)
        autoFlag(nullable: true)
        autoInterval(nullable: true)

        creator(nullable: false)
        updater(nullable: true)
    }
    static mapping = {
        version false
    }

    //特殊处理-符合layuitable模型
    def toLayUiTableModel(params){
        def toolbar = SysCommUtil.Clob2String(this.toolbar)
        def cols = this.getLayUiColsModel(params)

        return [elem:"#${domId}",tableId:this.id,widgetPanelId:widgetPanelId,
                toolbar:( ["false","true"].contains(toolbar))?Boolean.parseBoolean(toolbar):toolbar,
                defaultToolbar:defaultToolbar,url:this.url,
                width:width,height:height,cellMinWidth:cellMinWidth,totalRow:Boolean.parseBoolean(totalRow?:"false"),
                page:Boolean.parseBoolean(page),title:title,method:"post",
                id:domId,skin:skin,size:size_,even:even,queryFlag:Boolean.parseBoolean(queryFlag) ,
                autoFlag:Boolean.parseBoolean(autoFlag),autoInterval:autoInterval,cols:cols,mergeField:mergeField]
    }

    //特殊处理-符合layui table-col模型
    def mergeField = []
    def getLayUiColsModel(params){
        def result = XdTableColCfg.findAll("from XdTableColCfg as a where a.xdTableId= :xdTableId order by a.grade,a.colIndex",[xdTableId:this.id])

        def temp = []
         result.each {
             def item = it.toLayUiColsModel(params)
             temp.add(item)
             //如果当前报表不分页，则表示需判定单元格合并
             if(this.page =="false" && item.mergeField  ){
                 mergeField.add(item.mergeField)
             }
        }
        List data = new ArrayList()
        temp = temp.groupBy {it.grade}
        temp.each {key,value ->
            data.add(value)
        }
        return  data
    }

    /**
     * 获取table配置的实际field,下载、上传使用模板使用
     * @param params
     * @return
     */
    def getColsField(){
        def result = XdTableColCfg.findAll("from XdTableColCfg as a where a.xdTableId= :xdTableId and a.field is not null and a.type='normal' order by a.grade,a.colIndex",[xdTableId:this.id])
        List<XdCell[]> data = new ArrayList()
        XdCell[] xdCellArray = new XdCell[result.size()]
        result.eachWithIndex {it,index ->
            xdCellArray[index] =  new XdCell(field:it.field,title: it.title,type: it.type,dataType: it.dataType)
        }
        data.add(xdCellArray)
        return  data
    }

    /**
     * 根据tableName生成insert-导入语句
     * 导入语句
     * @param tableName
     */
    def createInsertSql(tableName){
        def cols = XdTableColCfg.findAllByXdTableIdAndFieldIsNotNullAndType(this.id,"normal")
        def sb = new StringBuffer("insert into ${tableName}(")
        def value = new StringBuffer("values(")
        cols.eachWithIndex {item,index ->
            if(item.field){
                if(item.primaryKey == "Ora-seq" ){//如果是Oracle主键
                    if(item.primaryValue){//主键值不为空 , 主键值为空:自增主键
                        sb.append("${item.field},")
                        value.append("${item.primaryValue},")
                    }
                }else if( item.primaryKey && item.primaryKey != "Ora-seq" ){//如果是其他，则无需拼接

                }else {//如果不是主键
                    sb.append("${item.field},")
                    value.append(":${item.field},")
                }
            }
        }
        sb = sb.substring(0,sb.length() -1)
        value = value.substring(0,value.length() -1)
        return  "${sb})${value})"
    }


    /**
     * 根据table配置的逻辑主键，去删除数据
     * @param tableName
     */
    def createDeleteSql(tableName){
        def cols =  XdTableColCfg.findAllByXdTableIdAndFieldIsNotNullAndType(this.id,"normal")
        def sb = new StringBuffer("DELETE FROM ${tableName} WHERE 1=1 ")
        def whereSql = new StringBuffer()

        cols.eachWithIndex {item,index ->
            if(item.combKey  == "true"  ){//根据主键删除
                whereSql.append(" and ${item.field} = :${item.field}")
            }
        }

        if(!whereSql){//如果where条件为空，则不允许删除
            sb = ""
        }else{
            sb.append(whereSql)
        }
        return   sb.toString()
    }


    /**
     * 根据table配置的逻辑主键，去删除数据
     * @param tableName
     */
    def createUpdateSql(tableName){
        def cols =  XdTableColCfg.findAllByXdTableIdAndFieldIsNotNullAndType(this.id,"normal")

        def setSql = new StringBuffer(" set ")
        def whereSql = new StringBuffer(" where 1=1 ")

        cols.eachWithIndex {item,index ->
            if(!item.primaryKey){
                setSql.append(" ${item.field} = :${item.field},")
            }

            if( item.combKey  == "true" ){//根据主键更新
                whereSql.append(" and ${item.field} = :_${item.field}")
            }
        }

        if(whereSql.indexOf(":_") <0){//说明未配置任何主键,则不更新
            whereSql.append(" and 2=1 ")
        }
        def result = String.valueOf("update ${tableName} ${setSql.substring(0,setSql.length()-1)} ${whereSql}")

        return   result
    }
}
